//
//  UserProfile.m
//  Speedater
//
//  Created by NgoThang on 12/30/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "UserProfile.h"
#import "asyncimageview.h"
#import "Start.h"
#import "Login.h"
#import "ChangePassword.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface UserProfile (Private)

- (void)cleanup;

@end

@implementation UserProfile (Private)

- (void)cleanup
{
    self.myTabBar = nil;
    self.myScrollView = nil;
    self.lightImageView = nil;
    self.avatarImageView = nil;
    self.lightRedButton = nil;
    self.lightYellowButton = nil;
    self.lightGreenButton = nil;
    self.pickImageButton = nil;
    self.submitButton = nil;
    self.deleteButton = nil;
    self.changePasswordButton = nil;
    self.genderLabel = nil;
    self.searchGenderLabel = nil;
    self.ageLabel = nil;
    self.sizeLabel = nil;
    self.weightLabel = nil;
    self.placeTextField = nil;
    self.hairColorTextField = nil;
    self.profesionTextField = nil;
    self.hobbiesTextField = nil;
    self.aboutMeTextView = nil;
    self.dataActionSheet = nil;
    self.dataPickerView = nil;
}

@end


@implementation UserProfile

@synthesize myTabBar;
@synthesize myScrollView;
@synthesize lightImageView, avatarImageView;
@synthesize lightRedButton, lightYellowButton, lightGreenButton, pickImageButton, submitButton, deleteButton, changePasswordButton;
@synthesize genderLabel, searchGenderLabel, ageLabel, sizeLabel, weightLabel;
@synthesize placeTextField, hairColorTextField, profesionTextField, hobbiesTextField;
@synthesize aboutMeTextView;
@synthesize dataActionSheet, dataPickerView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"USERPROFILE -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (void)hideKeyBoard
{
    [placeTextField resignFirstResponder];
    [hairColorTextField resignFirstResponder];
    [profesionTextField resignFirstResponder];
    [hobbiesTextField resignFirstResponder];
}

-(void)showTrafficLight:(NSString *)val
{
    if([val isEqualToString:@"0"]) { 
        trafficLightInt = 0;
        [self.lightImageView setImage:[UIImage imageNamed:@"light_red.png"]];    
    }
    if([val isEqualToString:@"1"]) {
        trafficLightInt = 1;
        [self.lightImageView setImage:[UIImage imageNamed:@"light_yellow.png"]];    
    }
    if([val isEqualToString:@"2"]) {
        trafficLightInt = 2;
        [self.lightImageView setImage:[UIImage imageNamed:@"light_green.png"]];
    }
}

- (IBAction)lightRedButtonClick:(id)sender
{
    [self showTrafficLight:@"0"];
}

- (IBAction)lightYellowButtonClick:(id)sender
{
    [self showTrafficLight:@"1"];
}

- (IBAction)lightGreenButtonClick:(id)sender
{
    [self showTrafficLight:@"2"];
}

- (void)peseudoReload
{

}

- (void)showActionSheet3
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
   
    
    [actionSheet addButtonWithTitle:@"Photo-Bibliothek"];
    [actionSheet addButtonWithTitle:@"Gespeicherte Fotoalbum"];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        [actionSheet addButtonWithTitle:@"Kamera"];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [actionSheet release];
}

- (IBAction)pickImageButtonClick:(id)sender
{    
    [self showActionSheet3];
    curentTargetControl = pickImageButton;
}

- (IBAction)submitButtonClick:(id)sender
{
    // hide keyboard
    [self hideKeyBoard];
    
    // save profile mode
    requestMode = 2;
    
    NSString *postString = [NSString stringWithFormat:@"op=updateprofile&username=%@&ampel=%d&geschlecht=%@&suche=%@&wohnort=%@&haarfarbe=%@&alter=%@&grobe=%@&gewicht=%@&beruf=%@&hobbies=%@&aboutme=%@", 
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"], 
                            trafficLightInt, 
                            genderLabel.text, 
                            searchGenderLabel.text,
                            placeTextField.text,
                            hairColorTextField.text,
                            ageLabel.text,
                            sizeLabel.text,
                            weightLabel.text,
                            profesionTextField.text,
                            hobbiesTextField.text,
                            [AppDelegate encodeText:aboutMeTextView.text]];
    
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
//        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (IBAction)deleteButtonClick:(id)sender
{
     UIAlertView *alert = [[UIAlertView alloc]
                           initWithTitle:NSLocalizedString(@"Are you sure you want to delete your account?", nil)
                           message:nil
                           delegate:self 
                           cancelButtonTitle:NSLocalizedString(@"Cancel", nil) 
                           otherButtonTitles:NSLocalizedString(@"Ok", nil), nil];
    
    [alert show];
    [alert release];
}

- (void)goDeleteAccount
{
    requestMode = 3;
    
    NSString *postString = [NSString stringWithFormat:@"op=deleteAccount&username=%@&emailSub=%@&emailBody=%@",
                            [[NSUserDefaults standardUserDefaults] stringForKey:@"username"],
                            NSLocalizedString(@"delaccount_email_subject", @""), 
                            NSLocalizedString(@"delaccount_email_body", @"")];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];  
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex) {
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(goDeleteAccount) userInfo:nil repeats:NO];

    }
}

- (IBAction)changePasswordButtonClick:(id)sender
{
    ChangePassword *changePassword = [[ChangePassword alloc] init];
    [self.navigationController pushViewController:changePassword animated:YES];
    [changePassword release];
}

- (void)dismissActionSheet:(id)sender
{
    [myActionSheet dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)showActionSheet1
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    [actionSheet addButtonWithTitle:@"Männlich"];
    [actionSheet addButtonWithTitle:@"Weiblich"];
    [actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    [actionSheet release];
}

- (void)genderLabelClick:(id)sender
{
    [self showActionSheet1];
    
    // set current controll
    curentTargetControl = (UIControl *)genderLabel;
}

- (void)searchGenderLabelClick:(id)sender
{
    [self showActionSheet1];
    
    // set current controll
    curentTargetControl = (UIControl *)searchGenderLabel;
}

- (void)showActionSheet2
{
    // hide keyboard first
    [self hideKeyBoard];
    
    // show action
    if (myActionSheet != nil){
        [myActionSheet release];
        myActionSheet = nil;
    }
    myActionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                delegate:nil
                                       cancelButtonTitle:nil
                                  destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
    
    [myActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [pickerView selectRow:[dataPickerView indexOfObject:[(UILabel *)curentTargetControl text]] inComponent:0 animated:YES];
    
    [myActionSheet addSubview:pickerView];
    [pickerView release];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"zurück"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(240, 7.0f, 70.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [myActionSheet addSubview:closeButton];
    [closeButton release];
    
    [myActionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [myActionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}

- (void)ageLabelClick:(id)sender
{
    curentTargetControl = (UIControl *)ageLabel;
    
    [dataPickerView removeAllObjects];
    for (int i=14; i<=99; i++)
    {
        [dataPickerView addObject:[NSString stringWithFormat:@"%d", i]];
    }

    [self showActionSheet2];
}

- (void)sizeLabelClick:(id)sender
{
    curentTargetControl = (UIControl *)sizeLabel;
    
    [dataPickerView removeAllObjects];
    for (float i=1.20; i<=2.50; i += 0.05)
    {
        [dataPickerView addObject:[NSString stringWithFormat:@"%.2f m", i]];
    }
    
    [self showActionSheet2];
}

- (void)weightLabelClick:(id)sender
{
    curentTargetControl = (UIControl *)weightLabel;
    
    [dataPickerView removeAllObjects];
    for (int i=30; i<=150; i += 5)
    {
        [dataPickerView addObject:[NSString stringWithFormat:@"%d kg", i]];
    }
    
    [self showActionSheet2];
}

- (void)loadProfile
{    
    // load profile mode
    requestMode = 1;
    
    NSString *postString = [NSString stringWithFormat:@"op=loadprofile&username=%@&username_psudo=", [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData]; 
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

-(NSMutableData *)generateDataFromText:(NSString *)dataText fieldName:(NSString *)fieldName
{
	NSString *post = [NSString stringWithFormat:@"\r\n--0xKhTmLbOuNdArY\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n", fieldName];
    // Get the post header int ASCII format:
    NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    // Generate the mutable data variable:
    NSMutableData *postData = [[[NSMutableData alloc] initWithLength:[postHeaderData length]] autorelease];
    [postData setData:postHeaderData];
    
	NSData *uploadData = [dataText dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	
    // Add the text:
    [postData appendData: uploadData];
    
    // Add the closing boundry:
    [postData appendData: [@"\r\n" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
    
    // Return the post data:
    return postData;
}

- (NSData *)generatePostDataForData:(NSData *)uploadData fileName:(NSString *)fileName
{
    // Generate the post header:
	
    NSString *post = [NSString stringWithFormat:@"\r\n--0xKhTmLbOuNdArY\r\nContent-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\nContent-Type: application/octet-stream\r\n\r\n", fileName];
    
    // Get the post header int ASCII format:
    NSData *postHeaderData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    
    // Generate the mutable data variable:
    NSMutableData *postData = [[[NSMutableData alloc] initWithLength:[postHeaderData length]] autorelease];
    [postData setData:postHeaderData];
    
    // Add the image:
    [postData appendData: uploadData];
    
    // Add the closing boundry:
    [postData appendData: [@"\r\n--0xKhTmLbOuNdArY--" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
    
    // Return the post data:
    return postData;
}

-(UIImage *)resizeImage:(UIImage *)image:(NSInteger) width:(NSInteger) height 
{
	CGSize newSize = CGSizeMake(width, height);
    UIGraphicsBeginImageContext( newSize );
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)saveAvatarImage
{
    // check avatar image set
    if (!avatarIsChanged)
        return;
    
    NSData *imageData_ = UIImageJPEGRepresentation(self.avatarImageView.image, 1.0);
    
    NSString *urlString = [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"];
    
    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:urlString]];
	[request setHTTPMethod:@"POST"];
    
    NSMutableData *postData = [self generateDataFromText:@"upload" fieldName:@"op"];
    [postData appendData:[self generateDataFromText:[[NSUserDefaults standardUserDefaults] stringForKey:@"username"] fieldName:@"username"]];
    
    [postData appendData:[self generatePostDataForData:imageData_ fileName:@"speeddataimg.jpg"]];
    
    [request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
	[request addValue:@"multipart/form-data; boundary=0xKhTmLbOuNdArY" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody: postData];
	// setting the body of the post to the reqeust
	[request setHTTPBody:postData];
    
    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

- (void)goStart
{
    // goto Start form
    for (UIViewController *vc in self.navigationController.viewControllers)
        if ([vc isKindOfClass:[Start class]]){
            //NSLog(@"USERPROFILE -> popToViewController: %@", vc);
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
}

- (void)goBack
{
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Custom notifications

- (void)keyboardWillHide:(NSNotification *)noti
{    
    NSDictionary *userInfo = [noti userInfo];
    
    // restore size of scrollview
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    // only this form
    CGRect rect = self.view.bounds;
    rect.size.height -= 44;
    
    [self.myScrollView setFrame:rect];
    [UIView commitAnimations];
    
    keyboardIsShown = NO;
}
- (void)keyboardWillShow:(NSNotification *)noti
{
    // keyboard is already shown.
    if (keyboardIsShown) {
        return;
    }
    
    NSDictionary *userInfo = [noti userInfo];
    
    // get the size of the keyboard
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect newTextViewFrame = self.view.bounds;
    newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // keyboard animation duration value
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // resize the scrollview
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [self.myScrollView setFrame:newTextViewFrame];
    [UIView commitAnimations];
    
    keyboardIsShown = YES;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"USERPROFILE -> viewDidLoad");
    [super viewDidLoad];
    
    // navigation bar
    self.navigationController.navigationBar.hidden = NO;
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // scroll view
    [self.myScrollView setContentSize:CGSizeMake(320, 1000)];
    
    // navigation title
    self.title = @"Profil bearbeiten";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Zurück" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // gender label
    UITapGestureRecognizer *tgrGenderLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(genderLabelClick:)] autorelease];
    [self.genderLabel addGestureRecognizer:tgrGenderLabel];
    
    // search gender label
    UITapGestureRecognizer *tgrSearchGenderLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchGenderLabelClick:)] autorelease];
    [self.searchGenderLabel addGestureRecognizer:tgrSearchGenderLabel];
    
    // age label
    UITapGestureRecognizer *tgrAgeLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(ageLabelClick:)] autorelease];
    [self.ageLabel addGestureRecognizer:tgrAgeLabel];
    
    // size label
    UITapGestureRecognizer *tgrSizeLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sizeLabelClick:)] autorelease];
    [self.sizeLabel addGestureRecognizer:tgrSizeLabel];
    
    // weight label
    UITapGestureRecognizer *tgrWeightLabel = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(weightLabelClick:)] autorelease];
    [self.weightLabel addGestureRecognizer:tgrWeightLabel];
    
    // init data
    dataActionSheet = [[NSMutableArray alloc] init];
    [dataActionSheet addObject:@"Männlich"];
    [dataActionSheet addObject:@"Weiblich"];
    
    dataPickerView = [[NSMutableArray alloc] init];
    
    // get avatar image
    AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(16, 10, 47, 43)];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]]];
	[asyncImage loadImageFromURL:avatarURL];
    [asyncImage setForImage:avatarImageView];
    avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
    [asyncImage release];
    
    // load user profile
    [self loadProfile];
    
    // register for keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:self.view.window];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:self.view.window];
    keyboardIsShown = NO;
}

- (void)viewDidUnload
{
    //NSLog(@"USERPROFILE -> viewDidUnload");
    [self cleanup];
    
    // unregister for keyboard notifications while not visible.
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillShowNotification 
                                                  object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:UIKeyboardWillHideNotification 
                                                  object:nil]; 
    
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //NSLog(@"USERPROFILE -> viewWillAppear");
    //NSLog(@"USERPROFILE -> viewControllers: %@", self.navigationController.viewControllers);
    
    // save state
    [AppDelegate saveState:0 withViewController:self];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
    
    // omit save
    omitSave = NO;
}

- (void)viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];
    //NSLog(@"USERPROFILE -> viewWillDisappear");
    
    // save profile
    if (!omitSave) {
        omitSave = YES;
        [self submitButtonClick:nil];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo {
    self.avatarImageView.image = [self resizeImage:img :300 :300];
    avatarIsChanged = YES;
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - 
#pragma mark - ActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)menu didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if ([curentTargetControl isKindOfClass:[UIButton class]]) {
        // open dialog
        if (buttonIndex == 0) return;
        
        // omit save
        omitSave = YES;
        
        UIImagePickerController * picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;    
        switch (buttonIndex) {
            case 1:
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                break;
            case 3:
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            default:
                break;
        }
        picker.allowsEditing = TRUE;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }
    else {
        switch (buttonIndex) {
            case 0:
                [(UILabel *) curentTargetControl setText:@"Männlich"];
                break;
            case 1:
                [(UILabel *) curentTargetControl setText:@"Weiblich"];
                break;
            default:
                break;
        }
    }
}

#pragma mark -
#pragma mark Picker View Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView 
{
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component 
{
	return [dataPickerView count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component 
{
	return [dataPickerView objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 
{
    [(UILabel *) curentTargetControl setText:[dataPickerView objectAtIndex:row]];
}

#pragma mark -
#pragma mark UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{
    [textField resignFirstResponder];
	return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    [self.myScrollView setContentOffset:CGPointMake(0, textField.frame.origin.y - (self.myScrollView.frame.size.height/2) + (isHideNav ? 0 : 44)) animated:YES];
}

#pragma mark -
#pragma mark UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{ 
    BOOL isHideNav = self.navigationController.navigationBarHidden;
    [self.myScrollView setContentOffset:CGPointMake(0, textView.frame.origin.y - (self.myScrollView.frame.size.height/2) + (isHideNav ? 0 : 44)) animated:YES];
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableDictionary *results = [responseString JSONValue];
    [responseString release];
    
    NSString *status = [results objectForKey:@"status"];
    //NSLog(@"%@", results);
    switch (requestMode) {
        case 1:
            [self showTrafficLight:[results objectForKey:@"myAmpel"]];
            genderLabel.text = [results objectForKey:@"myGeschlecht"];
            searchGenderLabel.text = [results objectForKey:@"mySuche"];
            placeTextField.text = [results objectForKey:@"myWohnort"];
            hairColorTextField.text = [results objectForKey:@"myHaarfarbe"];
            ageLabel.text = [results objectForKey:@"myAlter"];
            sizeLabel.text = [results objectForKey:@"myGrobe"];
            weightLabel.text = [results objectForKey:@"myGewicht"];
            profesionTextField.text = [results objectForKey:@"myBeruf"];            
            hobbiesTextField.text = [results objectForKey:@"myHobbies"];
            aboutMeTextView.text = [AppDelegate decodeText:[results objectForKey:@"myAboutme"]];
            break;
        case 2:
            if ([status isEqualToString:@"1"])
            {
                if (avatarIsChanged) {
                    @try {
                        [self saveAvatarImage];
                    }
                    @catch (NSException *ex){
                        //NSLog(@"Exception: %@", ex);
                    }
                }
                
                
                
                if (!omitSave){
                    
                    // omit save
                    omitSave = YES;
                    
                    [self goStart];
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                                    message:NSLocalizedString(@"Edit profile successfully!", nil)
                                                                   delegate:nil 
                                                          cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                                          otherButtonTitles:nil];
                    [alert show];
                    [alert release];
                }
                
//                
//                
//                AppDelegate *d = [[UIApplication sharedApplication] delegate];
//                UINavigationController *navController = [d.tabBarController.viewControllers objectAtIndex:d.tabBarController.selectedIndex];
//                UIViewController *visibleController = [navController.viewControllers objectAtIndex:[navController.viewControllers count]-1];
//                NSLog(@"ok: %@", visibleController);
//                [(UserProfile *)visibleController peseudoReload];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                                message:NSLocalizedString(@"Incidents occur, please check again!", nil)
                                                               delegate:nil 
                                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            break;
        case 3:
            if ([status isEqualToString:@"1"])
            {
                // omit save
                omitSave = YES;
                
                // goto Login form
                for (UIViewController *vc in self.navigationController.viewControllers)
                    if ([vc isKindOfClass:[Login class]]){
                        [self.navigationController popToViewController:vc animated:YES];
                    }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                                message:NSLocalizedString(@"Your Account had been deleted.", nil)
                                                               delegate:nil 
                                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            else 
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
                                                                message:NSLocalizedString(@"Delete your account failure.", nil)
                                                               delegate:nil 
                                                      cancelButtonTitle:NSLocalizedString(@"OK", nil) 
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
            break;
        default:
            break;
    }
    
    [responseData release];
    responseData = nil;

    // loading
    [HUD hide:YES];
}

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:nil];
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 2;
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
